﻿module Leaves.NeuroCryptography.ConversionLayers

open System

let FloatToChar value (alphabet : list<char>) =
    if (value < 0.0) || (value > 1.0) then
        failwith "value should be between 0.0 and 1.0"

    let floatIndex = value * (float alphabet.Length)
    let index = int(round floatIndex)

    let actualIndex = if index >= alphabet.Length then index - 1 else index

    alphabet.[actualIndex]

let CharToFloat value (alphabet : list<char>) =
    let possibleCharIndex = List.tryFindIndex (fun c -> c = value) alphabet

    let charIndex =
        match possibleCharIndex with
        | None -> failwith ("Illegal character " + value.ToString())
        | Some(x) -> x

    (float)charIndex / (float)alphabet.Length

let FloatifyString (str : string) alphabet =
    seq {
        for char in str do
            yield CharToFloat char alphabet
    } |> Seq.toList

let DefloatifyString values alphabet =
    seq {
        for value in values do
            yield FloatToChar value alphabet
    } |> Seq.toArray |> String.Concat